#include "Inventory.h"
#include <map>
#include <algorithm>

namespace 
{
	std::map<std::string, Item*> _palette;
}

Item::Item( const std::string& id ) :
	_id(id)
{
	_palette[id] = this;
}


const std::string& Item::getID() const
{
	return _id;
}

Item* Item::getItem( const std::string& id )
{
	return _palette[id];
}

Inventory::Inventory()
{

}

void Inventory::addItem( Item* item, uint32_t count /*= 1*/ )
{
	auto it = findItem(item);
	if (it != _items.end())
		it->count += count;
	else
	{
		ItemInstance instance;
		instance.item = item;
		instance.count = count;
		_items.push_back(instance);
	}
}

Inventory::ItemsArray::iterator Inventory::findItem( Item * item )
{
	ItemsArray::iterator it = std::find_if(_items.begin(), _items.end(), [item](const ItemInstance& i) { return i.item == item;});
	return it;
}
Inventory::ItemsArray::const_iterator Inventory::findItem( Item * item ) const
{
	ItemsArray::const_iterator it = std::find_if(_items.begin(), _items.end(), [item](const ItemInstance& i) { return i.item == item;});
	return it;
}

bool Inventory::hasItem( Item* item ) const
{
	return findItem(item) != _items.end();
}

void Inventory::removeItem( Item* item, uint32_t count /*= 1*/ )
{
	auto it = findItem(item);
	if (it != _items.end())
	{
		if (it->count <= count)
			_items.erase(it);
		else
			it->count -= count;
	}
}
